package shuashuami.hb.com.avtivity;

import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;
import java.util.Stack;

import shuashuami.hb.com.hbclient.R;
import shuashuami.hb.com.util.DeviceTool;
import shuashuami.hb.com.view.HbBottomBar;


/**
 * <b>类   名：</b>${TYPE_NAME} <br/>
 * <b>类描述：</b> <br/>
 * <b>创建人：</b>zhangqi<br/>
 * <b>创建时间：</b>2017/3/9<br/>
 * <b>修改人：</b>zhangqi<br/>
 * <b>修改时间：</b>2017/3/9<br/>
 * <b>修改备注：</b><br/>
 *
 * @version 1.0.0<br/>
 */
public abstract class AbActivity extends FragmentActivity {
    /**
     * 用来保存所有已打开的Activity
     */
    private static Stack<Activity> listActivity = new Stack<Activity>();

    /**
     * 全局的LayoutInflater对象，已经完成初始化.
     */
    protected LayoutInflater mInflater;


    protected ViewGroup ab_base;

    /**
     * 记录上次点击按钮的时间
     **/
    private long lastClickTime;

    /**
     * 按钮连续点击最低间隔时间 单位：毫秒
     **/
    public final static int CLICK_TIME = 500;

    public HbBottomBar bottomBar;

    private TextView my_status_bar;
    private RelativeLayout my_title_bar;
    private TextView titlebar_text;

    private ImageView btn_left;
    private ImageView btn_right;

    private TextView tv_right;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 设置activity为无标题栏
        mInflater = LayoutInflater.from(this);

        requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 将activity推入栈中
        listActivity.push(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 4.4以上的系统透明化状态栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        // 初始化ui
        initUI();
        // 初始化数据
        initData();
        // 事件监听
        initListener();
    }

    public void setLeftView() {
        if (btn_left == null) {
            btn_left = (ImageView) findViewById(R.id.btn_left);
        }
        btn_left.setVisibility(View.VISIBLE);
        btn_left.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    public void setLeftView(int resId) {
        setLeftView();
        btn_left.setImageResource(resId);

    }

    public void setRightView() {
        if (btn_right == null) {
            btn_right = (ImageView) findViewById(R.id.btn_right);
        }
        btn_right.setVisibility(View.VISIBLE);
    }

    public void setRightTextView(String str) {
        if (tv_right == null) {
            tv_right = (TextView) findViewById(R.id.titlebar_next);
        }
        tv_right.setText(str);
        tv_right.setVisibility(View.VISIBLE);
    }

    public void setRightTextViewListener(View.OnClickListener listener) {
        tv_right.setOnClickListener(listener);
    }

    public void setRightView(int resId) {
        setRightView();
        btn_right.setImageResource(View.VISIBLE);
    }

    public void setLeftViewListener(View.OnClickListener listener) {
        btn_left.setOnClickListener(listener);
    }

    public void setRightViewListener(View.OnClickListener listener) {
        btn_right.setOnClickListener(listener);
    }

    public void setTitleBarColor(int color) {
        my_status_bar.setBackgroundColor(color);
        my_title_bar.setBackgroundColor(color);
    }

    /**
     * 添加标题
     *
     * @param title    标题文字
     * @param isNormal 是否添加颜色
     */
    public void setTitleBar(String title, boolean isNormal) {
        if (my_status_bar == null) {
            my_status_bar = (TextView) findViewById(R.id.my_status_bar);
            my_title_bar = (RelativeLayout) findViewById(R.id.my_title_bar);
            titlebar_text = (TextView) findViewById(R.id.titlebar_text);
        }
        if (my_status_bar == null) return;
        titlebar_text.setText(title);
        if (isNormal) {
            setTitleBarColor(getResources().getColor(R.color.app_main));
        }
    }

    public void setTitleBar(String title) {
        setTitleBar(title, true);
    }

    public void setBottomBar() {
        bottomBar = new HbBottomBar(this);
        ab_base.addView(bottomBar);
    }


    public void setAbContentView(int resId) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        int paddingBottom = (int) DeviceTool.getNavigationBarHeight(this);
        ab_base = (ViewGroup) mInflater.inflate(resId, null);

        ab_base.setPadding(0, 0, 0, paddingBottom);
        setContentView(ab_base);
        verifyStoragePermissions(this);
        //最外层布局
//        setContentView(resId);
    }


    /**
     * 初始化ui
     **/
    protected abstract void initUI();

    /**
     * 初始化数据
     **/
    protected abstract void initData();

    /**
     * 初始化监听
     **/
    protected abstract void initListener();


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        saveInstanceState(outState);
        super.onSaveInstanceState(outState);
    }

    /**
     * 保存activity状态
     **/
    protected void saveInstanceState(Bundle outState) {

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();

    }

    public void onBack(View v) {
        finish();

    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 从栈中移除当前activity
        if (listActivity.contains(this)) {
            listActivity.remove(this);
        }
    }

    /**********************
     * activity跳转
     **********************************/
    public void openActivity(Class<?> targetActivityClass) {
        openActivity(targetActivityClass, null);
    }

    public void openActivity(Class<?> targetActivityClass, Bundle bundle) {
        Intent intent = new Intent(this, targetActivityClass);
        if (bundle != null) {
            intent.putExtras(bundle);
        }
        //  listActivity.add(0,targetActivityClass);
        startActivity(intent);
    }


    public Activity getCurrentActivity() {
        return listActivity.get(listActivity.size() - 1);

    }

    public static boolean isForeground(Context context, String className) {
        if (context == null || TextUtils.isEmpty(className))
            return false;
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list = am.getRunningTasks(1);
        if (list != null && list.size() > 0) {
            ComponentName cpn = list.get(0).topActivity;
            if (className.equals(cpn.getClassName()))
                return true;
        }
        return false;
    }

    public int a = 0;


    public void openActivityAndCloseThis(Class<?> targetActivityClass) {
        openActivity(targetActivityClass);
        this.finish();
    }

    public void openActivityAndCloseThis(Class<?> targetActivityClass, Bundle bundle) {
        openActivity(targetActivityClass, bundle);
        this.finish();
    }

    /**
     * 验证上次点击按钮时间间隔，防止重复点击
     */
    public boolean verifyClickTime() {
        if (System.currentTimeMillis() - lastClickTime <= CLICK_TIME) {
            return false;
        }
        lastClickTime = System.currentTimeMillis();
        return true;
    }

    /**
     * 收起键盘
     */
    public void closeInputMethod() {
        // 收起键盘
        View view = getWindow().peekDecorView();// 用于判断虚拟软键盘是否是显示的
        if (view != null) {
            InputMethodManager inputmanger = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputmanger.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    /**
     * 获取string
     *
     * @param mRid
     * @return
     */
    public String getStringMethod(int mRid) {
        return this.getResources().getString(mRid);
    }

    /**
     * 获取demin
     *
     * @param mRid
     * @return
     */
    protected int getDemonIntegerMethod(int mRid) {
        return (int) this.getResources().getDimension(mRid);
    }

    /**
     * 关闭所有(前台、后台)Activity,注意：请已BaseActivity为父类
     */
    protected static void finishAll() {
        int len = listActivity.size();
        for (int i = 0; i < len; i++) {
            Activity activity = listActivity.pop();
            activity.finish();
        }
    }

    protected void finishAllWithOutLast() {
        int len = listActivity.size() - 1;
        for (int i = len - 1; i >= 0; i--) {
            Activity activity = listActivity.get(i);
            activity.finish();
        }
    }


    /*****************
     * 双击退出程序
     ************************************************/
    private long exitTime = 0;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            //返回事件
            finish();
            return super.onKeyDown(keyCode, event);
        }
        return false;
    }

    /*
     * ************Fragement相关方法************************************************
     *
     */
    private Fragment currentFragment = null;


    /**
     * Fragment替换(当前destrory,新的create)
     */
    public void fragmentReplace(int target, Fragment toFragment, boolean backStack) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        String toClassName = toFragment.getClass().getSimpleName();
        if (manager.findFragmentByTag(toClassName) == null) {
            transaction.replace(target, toFragment, toClassName);
            if (backStack) {
                transaction.addToBackStack(toClassName);
            }
            transaction.commit();
        }
    }

    /**
     * Fragment替换(核心为隐藏当前的,显示现在的,用过的将不会destrory与create)
     */
    public void smartFragmentReplace(int target, Fragment toFragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction transaction = manager.beginTransaction();
        // 如有当前在使用的->隐藏当前的
        if (currentFragment != null) {
            transaction.hide(currentFragment);
        }
        String toClassName = toFragment.getClass().getSimpleName();
        // toFragment之前添加使用过->显示出来
        if (manager.findFragmentByTag(toClassName) != null) {
            transaction.show(toFragment);
        } else {// toFragment还没添加使用过->添加上去
            transaction.add(target, toFragment, toClassName);
        }
        transaction.commit();
        // toFragment更新为当前的
        currentFragment = toFragment;
    }

    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE };
    /**
     * Checks if the app has permission to write to device storage
     * If the app does not has permission then the user will be prompted to
     * grant permissions
     * @param activity
     */
    public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }
}
